/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

package com.huawei.housekeeper.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import lombok.extern.log4j.Log4j2;
import reactor.core.publisher.Mono;

/**
 * url解析
 *
 * @since 2022-02-16
 */
@Log4j2
@Component
public class DomainFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("request come in");

        ServerHttpRequest request = exchange.getRequest();
        if (request.getHeaders().get("Referer") != null) {
            log.info(request.toString());
            String domain = request.getHeaders().get("Referer").get(0);
            log.info("source domain " + domain);
            domain = domain.substring(7).split("\\.")[0];
            log.info("result domain " + domain);
            ServerHttpRequest newRequest = request.mutate().header("tenantDomain", domain).build();
            exchange.mutate().request(newRequest).build();
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -100;
    }
}
